package GUIs;

import Configs.Config;
import Controllers.GeneratetPDF;
import Controllers.HoaDonController;
import Controllers.HopDongController;
import Controllers.MyTableFormat;
import java.awt.event.KeyEvent;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;

public class f_nhanvien_nguoithue_qlhopdong extends javax.swing.JFrame {

    private static f_nhanvien_nguoithue_qlhopdong _instance; //Kiểm tra sự tồn tại của 2 instance trong cùng 1 form
    private final Config conn;
    private String msnv;
    private String cmndNguoiThue;
    private HopDongController hopDongControl;
    private HoaDonController hoaDonControl;
    private final MyTableFormat myFormat;
    private GeneratetPDF genPDF;

    public f_nhanvien_nguoithue_qlhopdong(Config conn) {
        this.conn = conn;
        initComponents();
        this.myFormat = new MyTableFormat();
        this.myFormat.formatTable(this.tbdshopdong);
        this.myFormat.formatTable(this.tbdshoadon);
    }

    public static f_nhanvien_nguoithue_qlhopdong getInstance(Config conn, String msnv, String cmnd) {
        if (_instance == null) {
            _instance = new f_nhanvien_nguoithue_qlhopdong(conn);
        }
        _instance.cmndNguoiThue = cmnd;
        _instance.msnv = msnv;
        _instance.hopDongControl = new HopDongController(_instance.conn);
        _instance.hoaDonControl = new HoaDonController(_instance.conn);
        return _instance;
    }

    public void createAndShowUI() {
        setVisible(true);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        popmenudshopdong = new javax.swing.JPopupMenu();
        menuxemchitiethopdong = new javax.swing.JMenuItem();
        sepleft1 = new javax.swing.JPopupMenu.Separator();
        menuthemhopdong = new javax.swing.JMenuItem();
        menuxoahopdong = new javax.swing.JMenuItem();
        sepleft2 = new javax.swing.JPopupMenu.Separator();
        menuthemhoadonleft = new javax.swing.JMenuItem();
        popmenudshoadon = new javax.swing.JPopupMenu();
        menuxemchitiethoadon = new javax.swing.JMenuItem();
        sepright1 = new javax.swing.JPopupMenu.Separator();
        menuthemhoadon = new javax.swing.JMenuItem();
        menuxoahoadon = new javax.swing.JMenuItem();
        pnchinh = new javax.swing.JPanel();
        btntim = new javax.swing.JButton();
        btnlammoi = new javax.swing.JButton();
        tftim = new javax.swing.JTextField();
        sptbdshopdong = new javax.swing.JScrollPane();
        tbdshopdong = new javax.swing.JTable();
        spdshoadon = new javax.swing.JScrollPane();
        tbdshoadon = new javax.swing.JTable();
        btnthemhd = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        menuxemchitiethopdong.setText("Xem chi tiết hợp đồng dưới định dạng PDF");
        menuxemchitiethopdong.setToolTipText("");
        menuxemchitiethopdong.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuxemchitiethopdongActionPerformed(evt);
            }
        });
        popmenudshopdong.add(menuxemchitiethopdong);
        popmenudshopdong.add(sepleft1);

        menuthemhopdong.setText("Thêm hợp đồng");
        menuthemhopdong.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuthemhopdongActionPerformed(evt);
            }
        });
        popmenudshopdong.add(menuthemhopdong);

        menuxoahopdong.setText("Xóa thông tin hợp đồng");
        menuxoahopdong.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuxoahopdongActionPerformed(evt);
            }
        });
        popmenudshopdong.add(menuxoahopdong);
        popmenudshopdong.add(sepleft2);

        menuthemhoadonleft.setText("Thêm mới hóa đơn");
        menuthemhoadonleft.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuthemhoadonleftActionPerformed(evt);
            }
        });
        popmenudshopdong.add(menuthemhoadonleft);

        menuxemchitiethoadon.setText("Xem hóa đơn  dưới định dạng PDF");
        menuxemchitiethoadon.setToolTipText("");
        menuxemchitiethoadon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuxemchitiethoadonActionPerformed(evt);
            }
        });
        popmenudshoadon.add(menuxemchitiethoadon);
        popmenudshoadon.add(sepright1);

        menuthemhoadon.setText("Thêm mới hóa đơn");
        menuthemhoadon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuthemhoadonActionPerformed(evt);
            }
        });
        popmenudshoadon.add(menuthemhoadon);

        menuxoahoadon.setText("Xóa thông tin hóa đơn");
        menuxoahoadon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuxoahoadonActionPerformed(evt);
            }
        });
        popmenudshoadon.add(menuxoahoadon);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Danh sách thông tin các hợp đồng");
        setResizable(false);
        setType(java.awt.Window.Type.UTILITY);

        btntim.setText("Tìm");
        btntim.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btntimActionPerformed(evt);
            }
        });

        btnlammoi.setText("Làm mới");
        btnlammoi.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnlammoiActionPerformed(evt);
            }
        });

        tftim.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tftimKeyPressed(evt);
            }
        });

        tbdshopdong.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "STT", "Mã số HĐ", "Thời điểm lập", "Tình trạng"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Object.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbdshopdong.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        tbdshopdong.setComponentPopupMenu(popmenudshopdong);
        tbdshopdong.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tbdshopdong.getTableHeader().setReorderingAllowed(false);
        sptbdshopdong.setViewportView(tbdshopdong);
        if (tbdshopdong.getColumnModel().getColumnCount() > 0) {
            tbdshopdong.getColumnModel().getColumn(0).setResizable(false);
            tbdshopdong.getColumnModel().getColumn(1).setResizable(false);
            tbdshopdong.getColumnModel().getColumn(2).setResizable(false);
            tbdshopdong.getColumnModel().getColumn(3).setResizable(false);
        }

        tbdshoadon.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "STT", "Mã HĐ", "Thời điểm lập", "Đóng từ tháng", "Đến tháng", "Năm"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbdshoadon.setComponentPopupMenu(popmenudshoadon);
        tbdshoadon.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tbdshoadon.getTableHeader().setReorderingAllowed(false);
        spdshoadon.setViewportView(tbdshoadon);
        if (tbdshoadon.getColumnModel().getColumnCount() > 0) {
            tbdshoadon.getColumnModel().getColumn(0).setResizable(false);
            tbdshoadon.getColumnModel().getColumn(1).setResizable(false);
            tbdshoadon.getColumnModel().getColumn(2).setResizable(false);
            tbdshoadon.getColumnModel().getColumn(3).setResizable(false);
            tbdshoadon.getColumnModel().getColumn(4).setResizable(false);
            tbdshoadon.getColumnModel().getColumn(5).setResizable(false);
        }

        btnthemhd.setText("Thêm hợp đồng");
        btnthemhd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnthemhdActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("DANH SÁCH HỢP ĐỒNG");

        javax.swing.GroupLayout pnchinhLayout = new javax.swing.GroupLayout(pnchinh);
        pnchinh.setLayout(pnchinhLayout);
        pnchinhLayout.setHorizontalGroup(
            pnchinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnchinhLayout.createSequentialGroup()
                .addComponent(sptbdshopdong, javax.swing.GroupLayout.PREFERRED_SIZE, 376, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(spdshoadon))
            .addGroup(pnchinhLayout.createSequentialGroup()
                .addComponent(tftim, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btntim)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnlammoi)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnthemhd)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(pnchinhLayout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 978, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        pnchinhLayout.setVerticalGroup(
            pnchinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnchinhLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                .addGroup(pnchinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btntim)
                    .addComponent(tftim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnlammoi)
                    .addComponent(btnthemhd))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnchinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(sptbdshopdong, javax.swing.GroupLayout.DEFAULT_SIZE, 468, Short.MAX_VALUE)
                    .addComponent(spdshoadon)))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnchinh, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(pnchinh, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void tftimKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tftimKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            this.searchHopDong();
        }
    }//GEN-LAST:event_tftimKeyPressed

    private void btntimActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btntimActionPerformed
        this.searchHopDong();
    }//GEN-LAST:event_btntimActionPerformed

    private void btnlammoiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnlammoiActionPerformed
        this.refreshDsHopDong();
    }//GEN-LAST:event_btnlammoiActionPerformed

    private void menuxemchitiethopdongActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuxemchitiethopdongActionPerformed
        int row = this.tbdshopdong.getSelectedRow();
        if (row != -1) {
            String maHopDong = this.tbdshopdong.getValueAt(row, 1).toString();
            this.genPDF = new GeneratetPDF(this.conn);
            this.genPDF.callOpen(this.genPDF.generateChiTietHopDong(this.msnv, maHopDong));
        } else {
            JOptionPane.showMessageDialog(this, "Bạn chưa chọn đối tượng hợp đồng để xem chi tiết!", "Thông báo", JOptionPane.WARNING_MESSAGE);
            this.tbdshopdong.requestFocus();
        }
    }//GEN-LAST:event_menuxemchitiethopdongActionPerformed

    private void menuthemhopdongActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuthemhopdongActionPerformed
        f_nhanvien_nguoithue_hopdong_them hopdong_them = f_nhanvien_nguoithue_hopdong_them.getInstance(this.conn, this.msnv, this.cmndNguoiThue);
        hopdong_them.createAndShowUI();
    }//GEN-LAST:event_menuthemhopdongActionPerformed

    private void menuxoahopdongActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuxoahopdongActionPerformed
        int row = this.tbdshopdong.getSelectedRow();
        if (row != -1) {
            if (JOptionPane.showConfirmDialog(this, "Xác nhận xóa hợp đồng này?\nLưu ý: các thông tin sẽ bị xóa vĩnh viễn.", "Xác nhận", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                String maHopDong = this.tbdshopdong.getValueAt(row, 1).toString();
                this.hopDongControl.Delete(maHopDong);
                this.refreshDsHopDong();
            }
        } else {
            JOptionPane.showMessageDialog(this, "Vui lòng chọn hợp đồng cần xóa!", "Thông báo", JOptionPane.WARNING_MESSAGE);
            this.tbdshopdong.requestFocus();
        }
    }//GEN-LAST:event_menuxoahopdongActionPerformed

    private void menuxemchitiethoadonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuxemchitiethoadonActionPerformed
        int row = this.tbdshoadon.getSelectedRow();
        if (row != -1) {
            String maHoaDon = this.tbdshoadon.getValueAt(row, 1).toString();
            this.genPDF = new GeneratetPDF(this.conn);
            try {
                this.genPDF.callOpen(this.genPDF.generateChiTietHoaDon(this.msnv, maHoaDon));
            } catch (ParseException ex) {
                Logger.getLogger(f_nhanvien_nguoithue_qlhopdong.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            JOptionPane.showMessageDialog(this, "Bạn chưa chọn đối tượng hóa đơn để xem chi tiết!", "Thông báo", JOptionPane.WARNING_MESSAGE);
            this.tbdshoadon.requestFocus();
        }
    }//GEN-LAST:event_menuxemchitiethoadonActionPerformed

    private void menuthemhoadonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuthemhoadonActionPerformed
        int row = this.tbdshopdong.getSelectedRow();
        if (row != -1) {
            String maHopDong = this.tbdshopdong.getValueAt(row, 1).toString();
            f_nhanvien_nguoithue_hoadon_them hoadon_them = f_nhanvien_nguoithue_hoadon_them.getInstance(this.conn, this.msnv, maHopDong);
            hoadon_them.createAndShowUI();

        }
    }//GEN-LAST:event_menuthemhoadonActionPerformed

    private void menuxoahoadonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuxoahoadonActionPerformed
        int row = this.tbdshoadon.getSelectedRow();
        if (row != -1) {
            if (JOptionPane.showConfirmDialog(this, "Xác nhận xóa hóa đơn này?\nLưu ý: các thông tin sẽ bị xóa vĩnh viễn.", "Xác nhận", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                String maHoaDon = this.tbdshoadon.getValueAt(row, 1).toString();
                try {
                    this.hoaDonControl.Delete(maHoaDon);
                    this.refreshDsHopDong();
                    this.refreshDsHoaDon();
                } catch (ParseException ex) {
                    Logger.getLogger(f_nhanvien_nguoithue_qlhopdong.class.getName()).log(Level.SEVERE, null, ex);
                }
                this.refreshDsHoaDon();
            }
        } else {
            JOptionPane.showMessageDialog(this, "Vui lòng chọn hóa đơn cần xóa!", "Thông báo", JOptionPane.WARNING_MESSAGE);
            this.tbdshoadon.requestFocus();
        }
    }//GEN-LAST:event_menuxoahoadonActionPerformed

    private void btnthemhdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnthemhdActionPerformed
        f_nhanvien_nguoithue_hopdong_them hopdong_them = f_nhanvien_nguoithue_hopdong_them.getInstance(this.conn, this.msnv, this.cmndNguoiThue);
        hopdong_them.createAndShowUI();
    }//GEN-LAST:event_btnthemhdActionPerformed

    private void menuthemhoadonleftActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuthemhoadonleftActionPerformed
        int row = this.tbdshopdong.getSelectedRow();
        if (row != -1) {
            String maHopDong = this.tbdshopdong.getValueAt(row, 1).toString();
            f_nhanvien_nguoithue_hoadon_them hoadon_them = f_nhanvien_nguoithue_hoadon_them.getInstance(this.conn, this.msnv, maHopDong);
            hoadon_them.createAndShowUI();

        }
    }//GEN-LAST:event_menuthemhoadonleftActionPerformed

    public void reloadForm() {
        try {
            this.myFormat.clearTable(this.tbdshopdong);
            this.tftim.setText(null);
            this.hopDongControl.Show(this.tbdshopdong, null, this.cmndNguoiThue);
            this.tbdshopdong.getSelectionModel().addListSelectionListener((ListSelectionEvent event) -> {
                try {
                    int row = f_nhanvien_nguoithue_qlhopdong.this.tbdshopdong.getSelectedRow();
                    this.myFormat.clearTable(this.tbdshoadon);
                    f_nhanvien_nguoithue_qlhopdong.this.hoaDonControl.Show(f_nhanvien_nguoithue_qlhopdong.this.tbdshoadon, f_nhanvien_nguoithue_qlhopdong.this.tbdshopdong.getValueAt(row, 1).toString());
                } catch (Exception ex) {
                    //throw exception
                }
            });
        } catch (Exception ex) {
            //throw exception
        }
    }

    public void refreshDsHopDong() {
        this.tftim.setText(null);
        this.myFormat.clearTable(this.tbdshopdong);
        this.hopDongControl.Show(this.tbdshopdong, null, this.cmndNguoiThue);
        this.myFormat.clearTable(this.tbdshoadon);
    }

    public void refreshDsHoaDon() {
        int row = this.tbdshopdong.getSelectedRow();
        if (row != -1) {
            this.myFormat.clearTable(this.tbdshoadon);
            this.hoaDonControl.Show(this.tbdshoadon, this.tbdshopdong.getValueAt(row, 1).toString());
        }
    }

    private void searchHopDong() {
        String txtsearh = this.tftim.getText().trim();
        if (!txtsearh.isEmpty()) {
            this.myFormat.clearTable(this.tbdshopdong);
            this.myFormat.clearTable(this.tbdshoadon);
            this.hopDongControl.Show(this.tbdshopdong, txtsearh, this.cmndNguoiThue);
        } else {
            JOptionPane.showMessageDialog(this, "Vui lòng nhập thông tin hợp đồng cần tìm!", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
            this.tftim.requestFocus();
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnlammoi;
    private javax.swing.JButton btnthemhd;
    private javax.swing.JButton btntim;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenuItem menuthemhoadon;
    private javax.swing.JMenuItem menuthemhoadonleft;
    private javax.swing.JMenuItem menuthemhopdong;
    private javax.swing.JMenuItem menuxemchitiethoadon;
    private javax.swing.JMenuItem menuxemchitiethopdong;
    private javax.swing.JMenuItem menuxoahoadon;
    private javax.swing.JMenuItem menuxoahopdong;
    private javax.swing.JPanel pnchinh;
    private javax.swing.JPopupMenu popmenudshoadon;
    private javax.swing.JPopupMenu popmenudshopdong;
    private javax.swing.JPopupMenu.Separator sepleft1;
    private javax.swing.JPopupMenu.Separator sepleft2;
    private javax.swing.JPopupMenu.Separator sepright1;
    private javax.swing.JScrollPane spdshoadon;
    private javax.swing.JScrollPane sptbdshopdong;
    private javax.swing.JTable tbdshoadon;
    private javax.swing.JTable tbdshopdong;
    private javax.swing.JTextField tftim;
    // End of variables declaration//GEN-END:variables
}
